//
//  CatSettinVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/17.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatSettinVController.h"
#import "CatSettingModel.h"
#import "CatSettingGroupModel.h"
#import "CatSettingCell.h"
#import "CatDetailSettingVController.h"
#import "CatTimingListVController.h"
#import "CatVoiceVController.h"
//#import "SD78Mp3Info.h"
//#import "DecoderG711.h"
#import "CatCapTableViewController.h"
#import "CatShareListViewController.h"
@interface CatSettinVController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *settingTableview;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIView *headerview;
@property(nonatomic,strong)UIView *footerview;
@property(nonatomic,copy)NSString *nickname;
@property(nonatomic,strong)FBDevicesList *devicesList;
@property(nonatomic,strong)dispatch_block_t delayed_static_task;
@property(nonatomic,strong)dispatch_source_t timer;
@property(nonatomic,strong)dispatch_source_t wake_up_timer;
@property(nonatomic,assign)BOOL cancelpost;
@property(nonatomic,assign)int version;

@end

@implementation CatSettinVController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
     self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    
    if (self.is_sucess) {
        
        [SVProgressHUD showWithDuration:15];
        // 创建延迟执行的任务
        _delayed_static_task = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
         
            [SVProgressHUD dismiss];
             self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
             self.settingTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
            [self getdata];
            [self.settingTableview reloadData];
        });
        // 延迟执行任务
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), _delayed_static_task);
    }else{
        
        self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
        self.settingTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
       
       [self getdata];
       [self.settingTableview reloadData];
    }
   

    
}

//昵称改变 数据源重新更新
- (void)reloadDevicesNickname:(NSNotification *)notification
{
     self.devicesList.nick = self.nickname;
    [self.devicesList bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self getdata];
            [self.settingTableview reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];
        });
    }];    
}

-(void)restore_devices_r700_result:(NSNotification*)notification
{

    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
    
    NSDictionary *recvMsg = [notification object];
    int val =  [[recvMsg objectForKey:@"value"] intValue];
    if (val == 0){

        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:3];
      
        [self.navigationController popToRootViewControllerAnimated:YES];
          
    }else{
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备失败", nil)];
    }
}



- (void)setup
{
    self.view.backgroundColor = [UIColor whiteColor];
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    UILabel *titleLabel  = [[UILabel alloc]init];
    titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0];
    titleLabel.text = NSLocalizedString(@"设置", nil);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, 80, 25);
    self.navigationItem.titleView = titleLabel;
}



- (void)selectLeftActionClick
{
    if (_delayed_static_task) {
        dispatch_block_cancel(_delayed_static_task);
        _delayed_static_task = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if(@available(iOS 15.0,*)){
      UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
      apperance.backgroundColor = [UIColor whiteColor];
      self.navigationController.navigationBar.standardAppearance = apperance;
      self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteDevices:) name:@"deleteDevices" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDevicesNickname:) name:@"reloadNickname" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restore_devices_r700_result:) name:@"restore_devices_r700_result" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devstClick:) name:@"devst" object:nil];
}

- (void)devstClick:(NSNotification*)notification
{
    
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid = [dict objectForKey:@"bid"];
    
    if (![bid isEqualToString:self.bid]) {
         return;
    }
    
     __weak CatSettinVController *weakSelf = self;

    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
        
        self.cancelpost = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            if (weakSelf.delayed_static_task) {
                dispatch_block_cancel(weakSelf.delayed_static_task);
                weakSelf.delayed_static_task = nil;
            }
            
            [SVProgressHUD dismiss];
            
             self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
             self.settingTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
            
            [self getdata];
            [self.settingTableview reloadData];
        });
    
    }else {
        self.cancelpost = NO;
    }
}

- (void)getdata
{
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    int status = self.devicesList.status;


    [self.dataArray removeAllObjects];
     self.dataArray = nil;
  
    [SVProgressHUD show];

    //获取服务器上的录音资源
    NSURL *url = [YKBusinessFramework get_g711a:_bid version:0];

    [AFNHTTPSRequest httpsRequestWithUrl:url errorHint:^(id errorData) {
        NSLog(@"data---%@",errorData);
        [SVProgressHUD dismiss];
        
    } result:^(id data) {
        NSLog(@"data---%@",data);
    
         /*
         {
           "reason" : "success",
           "data" : {
             "version" : 7,
             "fileId" : "AmYAAAABHABwdWJsaWMvcGV0L2s0bXpTOFhjeWVwVS5nNzExAAAAAAAC"
           },
           "code" : 0
         }
         */
        [SVProgressHUD dismiss];
        if ([[data objectForKey:@"code"] intValue] == 0) {
            NSDictionary *dict = [data objectForKey:@"data"];
            int version = [[dict objectForKey:@"version"] intValue];
            self.version = version;
        }
    }];
    
    
    
    CatSettingModel *model4_1 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"语音设置",nil) subTitle:@"" andType:0 status:NO];
    model4_1.device_status = status;
    CatSettingGroupModel *groupModel2 = [[CatSettingGroupModel alloc]init];
    groupModel2.groupTitle = NSLocalizedString(@"提醒设置",nil);
    groupModel2.dataArray = @[model4_1];
    
    
    CatSettingModel *model4_2 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"录音",nil) subTitle:@"" andType:0 status:NO];
    model4_2.device_status = status;
    
    
    CatSettingModel *model4_3 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"智能侦测",nil) subTitle:@"" andType:0 status:NO];
    model4_3.device_status = status;
    
   int support =  [[self.devicesList.function_support substringWithRange:NSMakeRange(4,1)] intValue];

    if (support) {
        groupModel2.dataArray = @[model4_1,model4_3,model4_2];
    }else{
        groupModel2.dataArray = @[model4_1,model4_2];
    }
    groupModel2.footerTitle = NSLocalizedString(@"若不录制默认语音是 开饭咯，来吃饭吧",nil);
    
    
    CatSettingModel *model5 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"设备分享", nil) subTitle:@"" andType:0 status:NO];
    model5.device_status = status;
    CatSettingModel *model6 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"设备信息",nil) subTitle:@"" andType:0 status:NO];

    
    model6.device_status = status;
    CatSettingModel *model7 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"恢复出厂设置", nil) subTitle:@"" andType:0 status:NO];
    model7.device_status = status;
    
    CatSettingGroupModel *groupModel3 = [[CatSettingGroupModel alloc]init];
    groupModel3.groupTitle = NSLocalizedString(@"其他", nil);
    groupModel3.dataArray = @[model5,model6,model7];
    


    [self.dataArray addObject:groupModel2];
    [self.dataArray addObject:groupModel3];

    
     self.headerview.backgroundColor = [UIColor clearColor];
     self.footerview.backgroundColor = [UIColor clearColor];
}


- (UITableView*)settingTableview
{
     if(!_settingTableview){
         _settingTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         _settingTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
         _settingTableview.dataSource = self;
         _settingTableview.delegate = self;
         _settingTableview.tableHeaderView = self.headerview;
         _settingTableview.tableFooterView = self.footerview;
        [_settingTableview registerClass:[CatSettingCell class] forCellReuseIdentifier:@"CatSettingCell"];
         _settingTableview.rowHeight = 50;
        [self.view addSubview:_settingTableview];
        [_settingTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _settingTableview;
}


- (UIView*)headerview
{
    if(!_headerview){
        _headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth,160)];
        _headerview.backgroundColor = [UIColor  clearColor];
        UIImageView *deviceImage = [[UIImageView alloc]init];
       [_headerview addSubview:deviceImage];
       [deviceImage mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(_headerview.mas_centerX);
           make.top.equalTo(_headerview.mas_top).offset(13);
           make.width.height.mas_equalTo(102);
       }];
       deviceImage.image = [UIImage imageNamed:@"cat_set_pet_feeder"];
    }
    
    UIButton *button = (UIButton*)[_headerview viewWithTag:13156];
    if(button){
      [button removeFromSuperview];
       button = nil;
    }
    
    UIButton *editButon = [[UIButton alloc]init];
    editButon.tag = 13156;
    editButon.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
   [editButon setTitleColor:[HexChangeRGB colorWithHexString:@"#333333"] forState:UIControlStateNormal];
   [_headerview addSubview:editButon];
   [editButon mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.equalTo(_headerview.mas_centerX);
       make.top.equalTo(_headerview.mas_top).offset(125);
       make.height.mas_equalTo(22);
       make.width.mas_equalTo(280);
   }];
    [editButon setTitle:self.devicesList.nick.length > 0 ? self.devicesList.nick : NSLocalizedString(@"宠物喂食器", nil) forState:UIControlStateNormal];
    [editButon addTarget:self action:@selector(editButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [editButon setImage:[UIImage imageNamed:@"cat_setting_edit"] forState:UIControlStateNormal];
    [editButon SG_imagePositionStyle:SGImagePositionStyleRight spacing:5];
    return _headerview;
}

- (UIView*)footerview
{
    if(!_footerview){
        _footerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth,100)];
        _footerview.backgroundColor = [UIColor  clearColor];
    }
    
   UIButton *_deleteButton = [[UIButton alloc]init];
    _deleteButton.backgroundColor = [UIColor whiteColor];
   [_deleteButton setTitle:NSLocalizedString(@"删除设备", nil) forState:UIControlStateNormal];
    _deleteButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
   [_deleteButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FF7316"] forState:UIControlStateNormal];
   [_deleteButton addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];
   [_footerview addSubview:_deleteButton];
   [_deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerY.equalTo(_footerview.mas_centerY);
       make.height.mas_equalTo(44);
       make.width.mas_equalTo(260);
       make.centerX.equalTo(_footerview.mas_centerX);
   }];
   _deleteButton.layer.cornerRadius = 22;
   _deleteButton.layer.masksToBounds = YES;
   _deleteButton.layer.borderWidth = 1.0;
   _deleteButton.layer.borderColor = [HexChangeRGB colorWithHexString:@"#FF7316"].CGColor;

    return _footerview;
}

- (void)deleteButtonClick
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确认删除设备", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];
        [YKBusinessFramework equesDelDeviceWithBid:self.bid];
    }];
   
    [alertController addAction:cancelButton];
    [alertController addAction:deleteButton];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)editButtonClick
{
    
    if (self.devicesList.status == 0) {
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"修改名称", nil) message:NSLocalizedString(@"设备昵称不超过十个字符\n超过不显示", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
   UITextField *oldTf = [alert textFieldAtIndex:0];
   oldTf.tag = 199;
   oldTf.placeholder = NSLocalizedString(@"equipment_nickname_settings", nil);
   alert.tag = 100;
  [alert show];
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)//修改昵称
    {
        if (buttonIndex == 1)
        {
            
            NSLog(@"设备昵称 = %@",[alertView textFieldAtIndex:0].text);
            NSString *name = [alertView textFieldAtIndex:0].text;
            if (name.length >= 10) {
                NSRange range = {0,10};
                self.nickname = [[alertView textFieldAtIndex:0].text substringWithRange:range];
            }else {
                NSRange range = {0,name.length};
                self.nickname = [[alertView textFieldAtIndex:0].text substringWithRange:range];
            }
            
            if (![Tooles isValidateNick:[[alertView textFieldAtIndex:0].text stringByReplacingOccurrencesOfString:@" " withString:@""]])
            {
                if ([alertView textFieldAtIndex:0].text.length == 0)
                {
                    UIAlertView *alertEmptyView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"输入设备昵称", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
                     alertEmptyView.tag = 101;
                    [alertEmptyView show];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"请输入中文,字母,数字或下划线", nil) duration:2];
                }
                return;
            }
            else
            {
                [YKBusinessFramework equesSetDeviceNickWithBid:self.bid Nick:self.nickname];
            }
        }
        else
        {
            [self.settingTableview reloadData];
             NSLog(@"取消修改设备昵称");
        }
    }

}


- (NSMutableArray*)dataArray
{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CatSettingGroupModel *model = self.dataArray[section];
    return model.dataArray.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
    CatSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatSettingCell" forIndexPath:indexPath];
    cell.deleteBlock = ^(CatSettingModel * _Nonnull model) {
        
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确定删除设备", nil) preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [SVProgressHUD show];
                [YKBusinessFramework equesDelDeviceWithBid:self.bid];
            }];
           
            [alertController addAction:cancelButton];
            [alertController addAction:deleteButton];
            [self presentViewController:alertController animated:YES completion:nil];
    };

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = datamodel;
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.devicesList.status == 0) {
        return;
    }
    

    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
    if([datamodel.title isEqualToString:@"基本功能设置"]){
        CatDetailSettingVController *vc = [[CatDetailSettingVController alloc]init];
        vc.bid = self.bid;
        vc.settingsType = 1;
       [self.navigationController pushViewController:vc animated:YES];
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"设备信息",nil)]){
        CatDetailSettingVController *vc = [[CatDetailSettingVController alloc]init];
        vc.bid = self.bid;
        vc.settingsType = 2;
       [self.navigationController pushViewController:vc animated:YES];
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"设备分享", nil)]){
        
        if (self.devicesList.is_share == 1) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"子用户无法在分享设备",nil) duration:2];
             return;
        }
        
        CatShareListViewController *sharevc = [[CatShareListViewController alloc]init];
        sharevc.bid = self.bid;
       [self.navigationController pushViewController:sharevc animated:YES];

    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"语音设置",nil)]){
     

        CatDetailSettingVController *vc = [[CatDetailSettingVController alloc]init];
        vc.bid = self.bid;
        vc.settingsType = 3;
       [self.navigationController pushViewController:vc animated:YES];
        
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"录音",nil)]){
        
    
        CatVoiceVController *infrared = [[CatVoiceVController alloc] init];
        infrared.version = self.version;
        infrared.bid = self.bid;
       [self.navigationController pushViewController:infrared animated:YES];
        
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"智能侦测",nil)]){
        
        
        CatCapTableViewController *Capturevc = [[CatCapTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        Capturevc.bid = self.devicesList.bid;
        if (Capturevc.modelArrary.count) {
           [Capturevc.modelArrary removeAllObjects];
        }
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:Capturevc animated:YES];
    }

    
    else if ([datamodel.title isEqualToString:NSLocalizedString(@"恢复出厂设置", nil)]){
      
    
        __weak CatSettinVController *weakSelf = self;
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
        if (list.status == 2) {
            [SVProgressHUD showWithDuration:15];
            // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
            __block int timeout = 30*200*5; // 倒计时时间
            _cancelpost = NO;
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
            dispatch_source_set_event_handler(_wake_up_timer, ^{
                if(weakSelf.cancelpost){ // 倒计时结束，关闭
                   
                    [self post_restore];

                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    weakSelf.wake_up_timer = nil;
                }else{
                    NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                    [YKBusinessFramework equesSendData:Str];
                     timeout-=200;
                    if (timeout <= 0) {
                        dispatch_source_cancel(weakSelf.wake_up_timer);
                        weakSelf.wake_up_timer = nil;
                    }
                }
            });
             dispatch_resume(weakSelf.wake_up_timer);
        }else if (list.status == 1){
            [self post_restore];
        }else{
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备不在线", nil)];
        }
    }
    
}

- (void)post_restore
{
    
    __weak CatSettinVController *weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确认恢复出厂设置", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
      
        __block int timeout = 15; // 倒计时时间
        
        NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"restore_devices_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100003070,\"value\":1}",[Tooles get_uid] ,weakSelf.bid];
        [YKBusinessFramework equesSendData:Str];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        weakSelf.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(weakSelf.timer,dispatch_walltime(NULL, 0),5*NSEC_PER_SEC, 0); //每5秒执行
        dispatch_source_set_event_handler(weakSelf.timer, ^{

            timeout -= 5;
            if (timeout < 0)
            {
                if (weakSelf.timer) {
                    dispatch_source_cancel(weakSelf.timer);
                    weakSelf.timer = nil;
                }
            }
          
            NSLog(@"恢复出厂设置");
            NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"restore_devices_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100003070,\"value\":1}",[Tooles get_uid] ,weakSelf.bid];
            [YKBusinessFramework equesSendData:Str];
            
        });
        
        dispatch_resume(weakSelf.timer);
    }];
   
    [alertController addAction:cancelButton];
    [alertController addAction:deleteButton];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 20;
    }else{
        return 0.1;
    }
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor clearColor];
     CatSettingGroupModel *model = self.dataArray[section];
     UILabel *_subTitleLabel = [[UILabel alloc]init];
     [view addSubview:_subTitleLabel];
     _subTitleLabel.textColor = [HexChangeRGB colorWithHexString:@"#778CA2"];
     _subTitleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.0];
     _subTitleLabel.numberOfLines = 0;
     _subTitleLabel.textAlignment = NSTextAlignmentLeft;
    [_subTitleLabel sizeToFit];
    [_subTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
       make.left.equalTo(view.mas_left).offset(14);
       make.centerY.equalTo(view.mas_centerY);
    }];
     _subTitleLabel.text = model.groupTitle;
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     CatSettingGroupModel *model = self.dataArray[section];
    if (model.footerTitle.length > 0) {
        UILabel *_subTitleLabel = [[UILabel alloc]init];
        [view addSubview:_subTitleLabel];
         view.backgroundColor = [UIColor clearColor];
        _subTitleLabel.textColor = [HexChangeRGB colorWithHexString:@"#808080"];
        _subTitleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.0];
        _subTitleLabel.numberOfLines = 0;
        _subTitleLabel.textAlignment = NSTextAlignmentLeft;
       [_subTitleLabel sizeToFit];
       [_subTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
          make.left.equalTo(view.mas_left).offset(14);
          make.right.equalTo(view.mas_right).offset(-14);
          make.top.equalTo(view.mas_top).offset(5);
       }];
        _subTitleLabel.text = model.footerTitle;
    }
    
     return view;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_delayed_static_task) {
        dispatch_block_cancel(_delayed_static_task);
        _delayed_static_task = nil;
    }
    
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadNickname" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"deleteDevices" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"restore_devices_r700_result" object:nil];

}

- (void)deleteDevices:(NSNotification *)notification
{
    if ([SVProgressHUD isVisible]) {
        [SVProgressHUD dismiss];
    }
     [self.navigationController popToRootViewControllerAnimated:YES];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];
    
}


@end
